package com.xbongbong.pro.statistic.help;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.pro.domain.entity.ChartCategoryEntity;
import com.xbongbong.pro.domain.entity.ChartEntity;
import com.xbongbong.pro.domain.entity.IndexSetEntity;
import com.xbongbong.pro.enums.BoardTypeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.index.pojo.IndexBoardChartSavePojo;
import com.xbongbong.pro.index.pojo.IndexSetDataPojo;
import com.xbongbong.pro.statistic.constant.ChartConstant;
import com.xbongbong.pro.statistic.enums.ChartCategoryAliasEnum;
import com.xbongbong.pro.statistic.enums.ChartCategoryTypeEnum;
import com.xbongbong.pro.statistic.enums.ChartPublishEnum;
import com.xbongbong.pro.statistic.enums.StatisticsTypeEnum;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.enums.MirrorModuleEnum;
import com.xbongbong.saas.help.IndexHelp;
import com.xbongbong.saas.model.IndexSetModel;
import com.xbongbong.sys.domain.entity.MirrorCompanyEntity;
import com.xbongbong.sys.domain.entity.MirrorInfoEntity;
import com.xbongbong.sys.model.MirrorCompanyModel;
import com.xbongbong.sys.model.MirrorInfoModel;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @Author: hongxiao
 * @date: 2020-12-23 19:22
 */
@Component
public class IndexInitHelp {
    private static final Logger LOG = LoggerFactory.getLogger(IndexInitHelp.class);
    @Resource
    private IndexSetModel indexSetModel;
    @Resource
    private MirrorCompanyModel mirrorCompanyModel;
    @Resource
    private MirrorInfoModel mirrorInfoModel;
    @Resource
    private IndexHelp indexHelp;

    public void initConfig(String corpid, List<ChartCategoryEntity> categoryList, List<ChartEntity> chartList) throws XbbException {
        // 公司配置是否存在
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(StringConstant.CORPID, corpid);
        param.put("userId", "0");
        param.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
        int count = indexSetModel.getEntitysCount(param);
        if (count > 0) {
            return;
        }

        // 公司是否启用镜像
        initMirrorConfig(corpid, categoryList, chartList);
        // 添加公司配置
        initCompanyConfig(corpid, categoryList, chartList);
    }

    /**
     *
     * @param categoryList
     * @param chartList
     * @author xingxing.xiao
     * @date 2019/12/05 17:28
     */
    private void initMirrorConfig (String corpid, List<ChartCategoryEntity> categoryList, List<ChartEntity> chartList) throws XbbException {

        // 公司若使用镜像，则根据镜像配置关闭相应的类别
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("columns", "version_id");
        param.put("corpid", corpid);
        param.put("del", 0);
        MirrorCompanyEntity mirrorCompany = mirrorCompanyModel.getMirrorCompany(param);
        if (Objects.nonNull(mirrorCompany)) {
            param.clear();
            param.put("columns", "id, module, info");
            param.put("versionId", mirrorCompany.getVersionId());
            param.put("moduleIn", Arrays.asList(MirrorModuleEnum.CATEGORY.getAlias(), MirrorModuleEnum.CHART.getAlias()));
            param.put("del", 0);
            List<MirrorInfoEntity> infoList = mirrorInfoModel.findEntitys(param);
            JSONArray categoryArray = new JSONArray();
            JSONArray categoryIdArray = new JSONArray();
            JSONObject chartObj = new JSONObject();
            for (MirrorInfoEntity entity : infoList) {
                if (Objects.equals(entity.getModule(), MirrorModuleEnum.CATEGORY.getAlias())) {
                    JSONObject categoryObj = JSONObject.parseObject(entity.getInfo());
                    categoryArray.addAll(categoryObj.getJSONArray("centerList"));
                    categoryArray.addAll(categoryObj.getJSONArray("todoSeries"));
                } else {
                    // chart镜像配置
                    chartObj = JSONObject.parseObject(entity.getInfo());
                }
            }

            // 设置要关闭的category
            for (ChartCategoryEntity chartCategory : categoryList) {
                if (!categoryArray.contains(chartCategory.getAlias())) {
                    chartCategory.setEnable(BasicConstant.NO_USE);
                } else {
                    // 记录 categoryId
                    categoryIdArray.add(chartCategory.getId());
                }
            }

            // 设置要关闭的chart(注：镜像中没有配置的category, 下面的chart不要设置为关闭)
            JSONArray chartArray = new JSONArray();
            for (Object obj : categoryArray) {
                JSONArray jsonArray = chartObj.getJSONArray(obj.toString());
                if (Objects.nonNull(jsonArray)) {
                    chartArray.addAll(jsonArray);
                }
            }
            for (ChartEntity chartEntity : chartList) {
                if (categoryIdArray.contains(chartEntity.getCategoryId()) && !chartArray.contains(chartEntity.getSystemCode())) {
                    chartEntity.setEnable(BasicConstant.NO_USE);
                }
            }
        }
    }

    /**
     * 初始化公司配置
     *
     * @param categoryList 分类数据
     * @param chartList    指标数据
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-02-28 21:05
     * @version v1.0
     * @since v1.0
     */
    private void initCompanyConfig(String corpid, List<ChartCategoryEntity> categoryList, List<ChartEntity> chartList) throws XbbException {

        List<IndexSetEntity> saveList = new ArrayList<>();

        // 已启用的指标的map
        Map<Long, List<IndexBoardChartSavePojo>> enableMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        // 未启用的指标的map
        Map<Long, List<IndexBoardChartSavePojo>> disableMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);

        // 指标列表
        for (ChartEntity entity : chartList) {
            // 过滤publish=0或publish=2的指标
            if (Objects.equals(ChartPublishEnum.NOT_PUBLISH.getCode(), entity.getPublish()) || Objects.equals(ChartPublishEnum.CANNOT_PUBLISH.getCode(), entity.getPublish())) {
                continue;
            }
            List<Long> cidList = entity.getCategory().toJavaList(Long.class);
            Long chartId = entity.getId();
            int enable = entity.getEnable();
            Integer sort = entity.getSort();
            int sortInt = sort == null ? 0 : sort;
            for (Long categoryId : cidList) {
                if (enable == BasicConstant.IS_USE) {
                    addMapData(enableMap, categoryId, chartId, sortInt, entity.getStatisticsType());
                } else {
                    addMapData(disableMap, categoryId, chartId, sortInt, entity.getStatisticsType());
                }
            }
        }


//         dingtalk端数据
        List<IndexSetDataPojo> dingtalkSetData = new ArrayList<>();
        // web端左侧数据
        List<IndexSetDataPojo> leftSetData = new ArrayList<>();
        // web端右侧数据
        List<IndexSetDataPojo> rightSetData = new ArrayList<>();
        // 专注模式下dingtalk左侧数据
        List<IndexSetDataPojo> focusDingtalkLeftSetData = new ArrayList<>();
        // 专注模式下dingtalk右侧数据
        List<IndexSetDataPojo> focusDingtalkRightSetData = new ArrayList<>();
        // 获取右侧看板默认list
        List<String> defaultRightBoard = indexHelp.getRightBoardAlias();

        // 分类
        for (ChartCategoryEntity entity : categoryList) {
            Long categoryId = entity.getId();
            IndexSetDataPojo appPojo = new IndexSetDataPojo();

            appPojo.setChartCategoryId(categoryId);
            appPojo.setChartCategoryType(ChartConstant.CHART_CATEGORY_TYPE_CATEGORY);
            appPojo.setEnable(entity.getEnable());
            // 没有自定义分类，设置statisticsType为1
            appPojo.setStatisticsType(StatisticsTypeEnum.SYSTEM_STATISTIC.getCode());
            // 默认展示方式
            ChartCategoryAliasEnum aliasEnum = ChartCategoryAliasEnum.getByAlias(entity.getAlias());
            if (aliasEnum == null) {
                continue;
            }
            appPojo.setShowType(aliasEnum.getShowType());
            // 移动端无：公告，客户关怀，客服
            boolean noAppIndex = aliasEnum.equals(ChartCategoryAliasEnum.ANNOUNCEMENT) ||
                    aliasEnum.equals(ChartCategoryAliasEnum.CUSTOMER_CARE) ||
                    aliasEnum.equals(ChartCategoryAliasEnum.KE_FU);

            // 启用的指标
            if (enableMap.containsKey(categoryId)) {
                // 排序
                List<IndexBoardChartSavePojo> enableList = enableMap.get(categoryId);
                enableList.sort((pojo1, pojo2) -> pojo2.getSort() - pojo1.getSort());
                appPojo.setEnableList(enableList);
            }
            // 未启用的指标
            if (disableMap.containsKey(categoryId)) {
                appPojo.setDisableList(disableMap.get(categoryId));
            }

            // 默认使用app端排序值
            appPojo.setSort(indexHelp.appBoardDefaultSort(aliasEnum.getAlias()));

            int type = entity.getType();
            ChartCategoryTypeEnum typeEnum = ChartCategoryTypeEnum.getEnumByCode(type);
            if (typeEnum == ChartCategoryTypeEnum.WEB_INDEX_LEFT) {
                dingtalkSetData.add(appPojo);
                if (StringUtils.isNotBlank(entity.getAlias()) && defaultRightBoard.contains(entity.getAlias())){
                    focusDingtalkRightSetData.add(appPojo);
                }else {
                    focusDingtalkLeftSetData.add(appPojo);
                }

                IndexSetDataPojo webPojo = new IndexSetDataPojo();
                BeanUtil.copyProperties(appPojo, webPojo);
                webPojo.setSort(indexHelp.webLeftBoardDefaultSort(aliasEnum.getAlias()));
                leftSetData.add(webPojo);

            } else if (typeEnum == ChartCategoryTypeEnum.WEB_INDEX_RIGHT) {
                IndexSetDataPojo webPojo = new IndexSetDataPojo();
                BeanUtil.copyProperties(appPojo, webPojo);
                webPojo.setSort(indexHelp.webRightBoardDefaultSort(aliasEnum.getAlias()));
                rightSetData.add(webPojo);
                if (!noAppIndex) {
                    dingtalkSetData.add(appPojo);
                    if (StringUtils.isNotBlank(entity.getAlias()) && defaultRightBoard.contains(entity.getAlias())){
                        focusDingtalkRightSetData.add(appPojo);
                    }else {
                        focusDingtalkLeftSetData.add(appPojo);
                    }
                }
            } else if (typeEnum == ChartCategoryTypeEnum.APP_INDEX) {
                dingtalkSetData.add(appPojo);
                if (StringUtils.isNotBlank(entity.getAlias()) && defaultRightBoard.contains(entity.getAlias())){
                    focusDingtalkRightSetData.add(appPojo);
                }else {
                    focusDingtalkLeftSetData.add(appPojo);
                }
            }
        }

        // 排序
        dingtalkSetData.sort((pojo1, pojo2) -> pojo2.getSort() - pojo1.getSort());
        leftSetData.sort((pojo1, pojo2) -> pojo2.getSort() - pojo1.getSort());
        rightSetData.sort((pojo1, pojo2) -> pojo2.getSort() - pojo1.getSort());
        focusDingtalkLeftSetData.sort((pojo1, pojo2) -> pojo2.getSort() - pojo1.getSort());
        focusDingtalkRightSetData.sort((pojo1, pojo2) -> pojo2.getSort() - pojo1.getSort());

        JSONArray dingtalkData = new JSONArray();
        dingtalkData.addAll(dingtalkSetData);
        IndexSetEntity dingtalkSetEntity = new IndexSetEntity(corpid, "0", BoardTypeEnum.DINGTALK.getCode(), dingtalkData);

        JSONArray leftData = new JSONArray();
        leftData.addAll(leftSetData);
        IndexSetEntity leftSetEntity = new IndexSetEntity(corpid, "0", BoardTypeEnum.WEB_LEFT.getCode(), leftData);

        JSONArray rightData = new JSONArray();
        rightData.addAll(rightSetData);
        IndexSetEntity rightSetEntity = new IndexSetEntity(corpid, "0", BoardTypeEnum.WEB_RIGHT.getCode(), rightData);

        JSONArray focusDingtalkLeftData = new JSONArray();
        focusDingtalkLeftData.addAll(focusDingtalkLeftSetData);
        IndexSetEntity focusDingtalkLeftSetEntity = new IndexSetEntity(corpid, "0", BoardTypeEnum.FOCUS_DINGTALK_CATEGORY.getCode(), focusDingtalkLeftData);

        JSONArray focusDingtalkRightData = new JSONArray();
        focusDingtalkRightData.addAll(focusDingtalkRightSetData);
        IndexSetEntity focusDingtalkRightSetEntity = new IndexSetEntity(corpid, "0", BoardTypeEnum.FOCUS_DINGTALK_WORK.getCode(), focusDingtalkRightData);

        saveList.add(dingtalkSetEntity);
        saveList.add(leftSetEntity);
        saveList.add(rightSetEntity);
        saveList.add(focusDingtalkLeftSetEntity);
        saveList.add(focusDingtalkRightSetEntity);
        try {
            indexSetModel.insertBatch(saveList);
        } catch (Exception e) {
            LOG.error("保存首页看板公司配置失败",e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
    }

    /**
     * map添加数据
     *
     * @param map   map
     * @param key   键:Long类型
     * @param value 值:Long类型
     * @param sort 排序
     * @param statisticsType 指标类型：1系统指标,2自定义指标
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-02-28 22:01
     * @version v1.0
     * @since v1.0
     */
    private void addMapData(Map<Long, List<IndexBoardChartSavePojo>> map, Long key, Long value, Integer sort, Integer statisticsType) {
        IndexBoardChartSavePojo savePojo = new IndexBoardChartSavePojo();
        savePojo.setId(value);
        savePojo.setSort(sort);
        savePojo.setStatisticsType(statisticsType);
        if (map.containsKey(key)) {
            map.get(key).add(savePojo);
        } else {
            List<IndexBoardChartSavePojo> list = new ArrayList<>();
            list.add(savePojo);
            map.put(key, list);
        }
    }

    /***
     * 添加发布到首的指标，放到头部
     *
     * @param chartEntity 发布到首布的指标
     * @throws
     * @return com.xbongbong.pro.index.pojo.IndexSetDataPojo
     * @author hongxiao
     * @date 2021-11-01 15:28
     * @since
     * @version
     */
    private IndexSetDataPojo addPublishChart(ChartEntity chartEntity) {
        IndexSetDataPojo publishChartDataPojo = new IndexSetDataPojo();

        publishChartDataPojo.setChartCategoryId(chartEntity.getId());
        publishChartDataPojo.setChartCategoryType(ChartConstant.CHART_CATEGORY_TYPE_CHART);
        publishChartDataPojo.setEnable(chartEntity.getEnable());
        // 没有自定义分类，设置statisticsType为1
        publishChartDataPojo.setStatisticsType(chartEntity.getStatisticsType());
        publishChartDataPojo.setShowType(chartEntity.getChartType());
        // 放到头部，分类sort最大值为20
        publishChartDataPojo.setSort(30);
        // 二级分类id
        List<Long> cidList = chartEntity.getCategory().toJavaList(Long.class);
        publishChartDataPojo.setSecondCategoryId(cidList.get(0));

        return publishChartDataPojo;
    }
}
